<?php
/***************************************************************************
*                                request.php
 *
 *   Begin date           	: 
 *   Copyright            	: 
 *   Email                	: 
 ***************************************************************************/
defined('PHP5_PHP') or die("Application is stopping!!!");

//error_reporting(E_STRICT | E_ALL);

// Provide AdWords login information.
$email = 'info@ua-solutions.com';
$password = 'uasolutions';
	
	$params = array(
		'Email' => $email,
		'Passwd' => $password,
		'accountType' => 'GOOGLE',
		'service' => 'adwords',
		'source' => 'AdWords API PHP Code Example');
	
	$url = 'https://www.google.com/accounts/ClientLogin';
	
	// Make request
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	$response = curl_exec($ch);
	curl_close($ch);
	
	// Parse response.
	$lines = explode("\n", $response);
	foreach ($lines as $line) {
	  $parts = explode('=', $line, 2);
	  if ($parts[0] == 'Auth') {
		$authToken = $parts[1];
	  }
	  if ($parts[0] == 'Error') {
		$error = $parts[1];
	  }
	}

//get
$task 		= php5GetParam($_REQUEST, 'task', '');
$during 		= php5GetParam($_REQUEST, 'during', 'TODAY');
$time_start 		= php5GetParam($_REQUEST, 'time_start', '');
$time_end 		= php5GetParam($_REQUEST, 'time_end', '');
if(!$time_start) {
	$date1 = date('Ymd', php5GMTTime());
	$time_start = date('d-m-Y', php5GMTTime());
} else {
	$arr = explode('-', $time_start);
	$date1 = $arr[2].$arr[1].$arr[0];
}
if(!$time_end) {
	$date2 = date('Ymd', php5GMTTime());
	$time_end = date('d-m-Y', php5GMTTime());
} else {
	$date2 = date('d-m-Y', php5GMTTime());
	$arr = explode('-', $time_end);
	$date2 = $arr[2].$arr[1].$arr[0];	
}
$user 		= php5GetParam($_REQUEST, 'user', '489-314-3321');
$currPage = php5GetParam($_REQUEST, 'p', 1);
if(!$currPage) {
	$currPage = 1;
}
$msg = '';
$smarty->setCompileDir(sprintf($php5RootAdminTempalteCPath, 'adwords'));
$tpl = sprintf($php5TemplateAdminFile, $language, 'adwords', 'reports.tpl');
if(!is_file($tpl )) {
	die("can not find template");
}


// Display results.
if (isset($authToken)) {
  //print 'Auth token: ' . $authToken . "\n";
} else if (isset($error)) {
  print 'Error: ' . $error . "\n";
}

// Provide header information.
//$authToken = 'INSERT_AUTH_TOKEN_HERE';
$clientCustomerId = $user;//'489-314-3321';
$userAgent = 'uasolutions: AdWords API PHP Code Example';
$developerToken = 'pEGGOZ84xYlJktXyXJnSKg';
// Provide header information.
$apiVersion = 'v201302';
// Create report definition XML.
$chk = $php5Session->getVar("chk");
$category_key = $php5Session->getVar("category_key");
$reportDefinition = 'SELECT ' . implode(",", $chk ) . ' ' .
  '  FROM '.$category_key.' DURING '.$date1.',' . $date2 
;
$format = 'CSV';

// Create parameters.
$params = array(
  '__rdquery' => $reportDefinition,
  '__fmt' => $format,
);

// Create headers.
$headers = array();
$headers[]= 'Authorization: GoogleLogin auth=' . $authToken;
$headers[]= 'clientCustomerId: ' . $clientCustomerId;
$headers[]= 'developerToken: ' . $developerToken;

$downloadPath = $php5RootPath . '/images/reports/report.csv';
$url = 'https://adwords.google.com/api/adwords/reportdownload/v201302';

$file = fopen($downloadPath, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($file);
$arrHeader = '';
$arrTitle = '';
$arrDatas = '';
if ($code == 200) {
  //printf("Report downloaded to: %s\n", $downloadPath);
	$line = readfile_chunked($downloadPath);
	$arrHeader = str_getcsv($line[0]);
	$arrTitle = str_getcsv($line[1]);
	
	if(count($line) > 1) {
		for($i=2;$i<count($line)-1;$i++) {
			$arrDatas[] = str_getcsv($line[$i]);
		}
	}
	
} else {
  $file = fopen($downloadPath, 'r');
  $error = fread($file, 1024);
  fclose($file);
  //printf("Error: %s\n", $error);
  $arr = XMLtoArray($error);
  if(isset($arr['REPORTDOWNLOADERROR']['APIERROR']['TRIGGER'])) {
	  $msgAlert = $arr['REPORTDOWNLOADERROR']['APIERROR']['TRIGGER'];
  } else if(isset($arr['REPORTDOWNLOADERROR']['APIERROR']['open']['content'])) {
	  $msgAlert = $arr['REPORTDOWNLOADERROR']['APIERROR']['open']['content'];
  } else {
	  $msgAlert = "System Error";
  }
}
$category_key = $php5Session->getVar("category_key");
$chk = $php5Session->getVar("chk");

$smarty->assign('arrDuring', $define->REPORT_DURING());
$smarty->assign('arrUser', $define->REPORT_USER());
$smarty->assign('during', $during);
$smarty->assign('time_start', $time_start);
$smarty->assign('time_end', $time_end);
$smarty->assign('user', $user);
$smarty->assign('title', $category_key);
$smarty->assign('arrHeader', $arrHeader);
$smarty->assign('arrTitle', $arrTitle);
$smarty->assign('arrDatas', $arrDatas);
$smarty->assign('msg', '');
$smarty->assign('action', sefBuild($php5WebPath, 'index.php?o=adwords&m=reports', 0));
$smarty->assign('item_url', sefBuild($php5WebPath, 'index.php?o=adwords&m=items', 0));
$smarty->assign('main', $smarty->fetch($tpl));
//$smarty->display($tpl);

return;

